package server

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/hxchjm/log"
	"io"
	"net/http"
)

type CustomResponseWriter struct {
	gin.ResponseWriter
	data []byte
}

func (r *CustomResponseWriter) Write(b []byte) (int, error) {
	r.data = append(r.data, b...)
	return r.ResponseWriter.Write(b)
}

func Logger(c *gin.Context) {
	c.Set("trace_id", uuid.New().String())

	responseWriter := &CustomResponseWriter{
		ResponseWriter: c.Writer,
	}
	c.Writer = responseWriter

	var bodyRes []byte
	switch c.Request.Method {
	case http.MethodPost:
		bodyRes, _ = io.ReadAll(c.Request.Body)
		c.Request.Body = io.NopCloser(bytes.NewReader(bodyRes))
	case http.MethodGet:
		bodyRes = []byte(c.Request.URL.Query().Encode())
	}

	c.Next()

	// 这里可以获得响应数据
	responseData := responseWriter.data
	statusCode := c.Writer.Status()
	// responseData 就是原始的响应数据，如果需要，可以在这里对其进行处理。
	var bs = bodyRes
	var m = make(map[string]interface{})
	_ = json.Unmarshal(bs, &m)
	reqStr, _ := json.Marshal(m)
	log.Infof(c, "url=%s ,request=%s ,response=%s ,code=%d", c.Request.URL.Path, reqStr, responseData, statusCode)
}
